import * as utils from '../utils'

function createCourse04 (gl: WebGLRenderingContext, dom: HTMLCanvasElement) {
  gl.clearColor(0.0, 0.0, 0.0, 1.0)
  gl.clear(gl.COLOR_BUFFER_BIT)
  const vectexShaderSrc = `
    attribute vec4 a_Position;
      void main() {
          gl_Position = a_Position;
          gl_PointSize = 10.0;
      }
    `

  const fragmentShaderSrc = `
    precision mediump float;
    uniform vec4 a_FragColor;
      void main() {
          gl_FragColor  = a_FragColor;
      }
    `
  const program = utils.initShaders(gl, vectexShaderSrc, fragmentShaderSrc)

  const aPosition = gl.getAttribLocation(program, 'a_Position')

  const aFragColor = gl.getUniformLocation(program, 'a_FragColor')

  const aPoints: [number, number][] = []
  const aColors: number[][] = []
  dom.addEventListener('click', function (event: MouseEvent) {
    gl.clearColor(0.0, 0.0, 0.0, 1.0)
    gl.clear(gl.COLOR_BUFFER_BIT)
    const { clientX, clientY } = event
    const { width, height, offsetLeft, offsetTop } = dom
    const x = (clientX - offsetLeft) / width * 2 - 1
    const y = -(clientY - offsetTop) / height * 2 + 1
    aPoints.push([x, y])

    if (x > 0 && y > 0) {
      aColors.push([1.0, 0.0, 0.0, 1.0])
    } else if (x < 0 && y > 0) {
      aColors.push([0.0, 1.0, 0.0, 1.0])
    } else if (x < 0 && y < 0) {
      aColors.push([0.0, 0.0, 1.0, 1.0])
    } else {
      aColors.push([1.0, 1.0, 1.0, 1.0])
    }

    for (let i = 0; i < aPoints.length; i++) {
      const [x, y] = aPoints[i]
      const [r, g, b, a] = aColors[i]
      gl.vertexAttrib3f(aPosition, x, y, 0.0)
      gl.uniform4f(aFragColor, r, g, b, a)
      gl.drawArrays(gl.POINTS, 0, 1)
    }
  })
}

export {
  createCourse04
}
